const db = require('../config/db.config.js');

// 获取未完成预约统计
exports.getPendingConsultationsCount = async (req, res) => {
  try {
    const [result] = await db.query(
      'SELECT COUNT(*) as pendingCount FROM Consultations WHERE status != "completed"'
    );
    res.json({ count: result[0].pendingCount });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 创建问诊订单
exports.createConsultation = async (req, res) => {
  try {
    console.log('用户信息:', req.user);
    console.log('请求头:', req.headers);
    console.log('请求体:', req.body);

    const {
      patient_name,
      phone,
      date,
      time,
      address,
      service_type,
      selected_services,
      total_price,
      order_type = 'custom',
      accompany_type,
      hospital_name,
      department,
    } = req.body;

    // 确保使用 token 中的用户名
    if (!req.user || !req.user.username) {
      console.log('未找到用户信息');
      return res.status(401).json({ message: '请先登录' });
    }
    const effectiveUsername = req.user.username;

    // 映射服务类型到数据库枚举值
    let dbServiceType = 'basic';
    if (service_type.includes('专科')) {
      dbServiceType = 'premium';
    } else if (service_type.includes('加急') || service_type.includes('vip')) {
      dbServiceType = 'vip';
    } else if (service_type.includes('陪诊')) {
      dbServiceType = 'accompany';
    }

    console.log('收到预约请求:', {
      patient_name,
      phone,
      date,
      time,
      address,
      service_type,
      username: effectiveUsername,
      selected_services,
      total_price,
      order_type,
      accompany_type,
      hospital_name,
      department,
      dbServiceType,
    });

    // 验证必填字段
    const requiredFields = {
      patient_name: !patient_name,
      phone: !phone,
      date: !date,
      time: !time,
    };

    // 根据服务类型验证额外字段
    if (service_type.includes('陪诊')) {
      requiredFields.hospital_name = !hospital_name;
      requiredFields.department = !department;
    } else {
      requiredFields.address = !address;
    }

    const missingFields = Object.entries(requiredFields)
      .filter(([_, isMissing]) => isMissing)
      .map(([field]) => field);

    if (missingFields.length > 0) {
      console.log('缺少必填字段:', missingFields);
      return res.status(400).json({
        message: '缺少必要字段',
        details: missingFields,
      });
    }

    // 开启事务
    const connection = await db.getConnection();
    await connection.beginTransaction();
    try {
      // 创建问诊订单
      const [result] = await connection.query(
        `INSERT INTO Consultations 
        (patient_name, phone, date, time, address, service_type, username, total_price, order_type, accompany_type, hospital_name, department) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          patient_name,
          phone,
          date,
          time,
          service_type.includes('陪诊') ? hospital_name : address || 'N/A', // 如果是陪诊服务，使用医院名称作为地址，否则使用地址或默认值
          dbServiceType, // 使用映射后的服务类型
          effectiveUsername,
          total_price,
          order_type,
          accompany_type || null,
          hospital_name || null,
          department || null,
        ]
      );

      const consultationId = result.insertId;
      console.log('创建预约成功，ID:', consultationId);

      // 如果是自定义预约且有选择额外服务，创建服务记录
      if (
        order_type === 'custom' &&
        selected_services &&
        selected_services.length > 0
      ) {
        console.log('添加自定义服务:', selected_services);
        const serviceValues = selected_services.map((service) => [
          consultationId,
          service,
          servicesPrices[service] || 0,
        ]);

        await connection.query(
          'INSERT INTO ConsultationServices (consultation_id, service_name, service_price) VALUES ?',
          [serviceValues]
        );
      }

      // 提交事务
      await connection.commit();
      console.log('事务提交成功');

      res.status(201).json({
        message: '问诊订单创建成功',
        consultationId,
        total_price,
      });
    } catch (error) {
      // 如果出错，回滚事务
      await connection.rollback();
      console.error('数据库操作失败，已回滚:', error);
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('创建预约失败:', error);
    res.status(500).json({
      message: '服务器错误',
      details:
        process.env.NODE_ENV === 'development' ? error.message : undefined,
    });
  }
};

// 服务价格配置
const servicesPrices = {
  // 上门医生
  basicDoctor: 199,
  premiumDoctor: 299,
  vipDoctor: 399,
  // 基础检查
  basicCheck: 99,
  bloodPressure: 39,
  bloodSugar: 49,
  ecg: 159,
  // 专科检查
  heartCheck: 299,
  lungFunction: 259,
  liverFunction: 199,
  kidneyFunction: 199,
  // 护理服务
  injection: 49,
  dressing: 79,
  catheter: 99,
  rehabilitation: 89,
  // 观察与咨询
  observation: 159,
  medication: 99,
  nutrition: 129,
  rehabPlan: 199,
  psychology: 259,
  familyGuidance: 499,
};

// 服务名称映射
const serviceNameMap = {
  // 上门医生
  basicDoctor: '普通医生上门',
  premiumDoctor: '专科医生上门',
  vipDoctor: '主任医生上门',
  // 基础检查
  basicCheck: '基础体检',
  bloodPressure: '血压测量',
  bloodSugar: '血糖检测',
  ecg: '心电图检查',
  // 专科检查
  heartCheck: '心脏专科检查',
  lungFunction: '肺功能检测',
  liverFunction: '肝功能检查',
  kidneyFunction: '肾功能检查',
  // 护理服务
  injection: '注射服务',
  dressing: '伤口换药',
  catheter: '导管护理',
  rehabilitation: '康复指导',
  // 观察与咨询
  observation: '病情观察',
  medication: '用药咨询',
  nutrition: '营养咨询',
  rehabPlan: '康复方案制定',
  psychology: '心理康复咨询',
  familyGuidance: '家庭康复指导',
};

// 获取问诊列表（管理员和护士可见所有，用户只能看到自己的）
exports.getConsultations = async (req, res) => {
  try {
    const username = req.user.username;
    const userRole = req.user.role;

    console.log('获取预约列表，用户角色:', userRole, '用户名:', username);

    // 基础查询
    let query = `
      SELECT 
        c.*,
        GROUP_CONCAT(DISTINCT cs.service_name ORDER BY cs.id) as selected_services,
        GROUP_CONCAT(DISTINCT cs.service_price ORDER BY cs.id) as service_prices
      FROM Consultations c
      LEFT JOIN ConsultationServices cs ON c.id = cs.consultation_id
    `;

    let params = [];

    // 普通用户只能看到自己的预约
    if (userRole === 'user') {
      query += ' WHERE c.username = ?';
      params.push(username);
    }

    // 分组以避免重复
    query += ' GROUP BY c.id ORDER BY c.created_at DESC';

    console.log('执行的SQL查询:', query);
    console.log('查询参数:', params);

    const [consultations] = await db.query(query, params);

    // 处理服务项目数据
    const formattedConsultations = consultations.map((consultation) => {
      const services = [];
      if (consultation.selected_services && consultation.service_prices) {
        const serviceNames = consultation.selected_services.split(',');
        const servicePrices = consultation.service_prices
          .split(',')
          .map(Number);

        for (let i = 0; i < serviceNames.length; i++) {
          services.push({
            service_name: serviceNameMap[serviceNames[i]] || serviceNames[i],
            service_price: servicePrices[i],
          });
        }
      }

      return {
        ...consultation,
        services,
        // 删除原始字段，避免数据重复
        selected_services: undefined,
        service_prices: undefined,
      };
    });

    res.json(formattedConsultations);
  } catch (error) {
    console.error('获取预约列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 更新问诊状态（管理员和护士权限）
exports.updateConsultationStatus = async (req, res) => {
  try {
    const { consultationId } = req.params;
    const { status } = req.body;

    const [result] = await db.query(
      'UPDATE Consultations SET status = ? WHERE id = ?',
      [status, consultationId]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '未找到问诊记录' });
    }

    res.json({ message: '状态更新成功' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};
